﻿using System;
using System.Collections.Generic;
using System.Text;
using AChance.Bll.Func;
using AChance.Dal.Func;
using AChance.Func;

namespace AChance.Bll.Trans
{
    public static class TrnCommon
    {
        /// <summary>
        /// 公用数据准备
        /// </summary>
        public static class Data
        {


        }
        /// <summary>
        /// 公用逻辑检查
        /// </summary>
        public static class Logic
        {
            /// <summary>
            /// 检查主键是否被引用
            /// </summary>
            public static void CheckKeyIsRef(string key)
            {
                string tableName = DalEntity.GetNameByKey(key);
                if (!BllLogic.Key.RefConfigs.ContainsKey(tableName))
                    return;
                foreach (var refConfig in BllLogic.Key.RefConfigs[tableName])
                {
                    if (refConfig.SyncExists || refConfig.KeyField.IsNullOrEmpty())
                        continue;
                    string sql = $"SELECT {refConfig.KeyField} FROM {refConfig.TableName} WHERE {refConfig.KeyField} = '{key}'";
                    if (DalOper.Sql.SelectExists(sql))
                        throw new Exception($"{DalEntity.GetDispName(tableName)}数据主键已被某些{DalEntity.GetDispName(refConfig.TableName)}数据关联");
                }
            }


        }
        /// <summary>
        /// 公用操作执行
        /// </summary>
        public static class Oper
        {
            /// <summary>
            /// 更新被引用的主键对应名称
            /// </summary>
            public static void UpdateRefKeyName(string key, string name)
            {
                string tableName = DalEntity.GetNameByKey(key);
                if (!BllLogic.Key.RefConfigs.ContainsKey(tableName))
                    return;
                foreach (var refConfig in BllLogic.Key.RefConfigs[tableName])
                {
                    if (refConfig.KeyField.IsNullOrEmpty() || refConfig.NameField.IsNullOrEmpty())
                        continue;
                    string sql = $"UPDATE {refConfig.TableName} SET {refConfig.NameField}='{name}' WHERE {refConfig.KeyField}='{key}'";
                    DalOper.Sql.UpdateRange(sql, $"{DalEntity.GetDispName(refConfig.TableName)}数据中的{DalEntity.GetDispName(tableName)}名称更新执行失败");
                }
            }


        }


    }
}
